package com.palrevo.beackBeans;

import java.io.File;
import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;


import com.palrevo.controllers.NavigationController;
import com.palrevo.controllers.NavigationRule;

import com.palrevo.common.Constants;
import com.palrevo.common.commands.Command;
import com.palrevo.data.models.Page;
import com.palrevo.data.models.User;
import com.palrevo.utils.Configs;
import com.palrevo.utils.WebUtils;

/**
 * 
 * @author AAsha
 *
 */
@ManagedBean(name="appSessionBean")
@SessionScoped
public class AppSessionBean {
	
	private static final String PAGE_ID = "PAGE_ID";
	
	private Page innerPage = new Page();
	
	private User user;
	
	private Command confirm;
	private Command cancel;
	
	/**
	 * 
	 */
	public AppSessionBean() {
	}
	
	public void openPage(){
		Object pageId = WebUtils.getRequest().getParameter(PAGE_ID);
		if(pageId == null){
			return;
		}
		
		ApplicationBean appBean = (ApplicationBean) WebUtils.resolveExpression(WebUtils.APP_BEAN, ApplicationBean.class);
		
		for(Page p:appBean.getPages().values()){
			if(p.getId().equals(Long.valueOf(pageId.toString()))){
				setInnerPage(p);
				break;
			}
		}
		
		NavigationController.navigate(NavigationRule.INNER_PAGE);
	}
	
	/**
	 * 
	 * @throws IOException
	 */
	public void downloadFile() throws IOException{
		
		Object fileName = WebUtils.getRequest().getParameter("FILE_NAME");
		if(fileName == null){
			return;
		}
		
		File filesDir = new File(Configs.getConfigValue(Constants.Configs.FILES_DIR));
        File file = new File(filesDir, fileName.toString());
        
        if(file.exists()){
        	WebUtils.downloadFile(file);
        }
	}
	
	public void confirm() throws Exception{
		confirm.execute();
	}
	
	public void cancel() throws Exception{
		cancel.execute();
	}
	
	public Command getConfirm() {
		return confirm;
	}

	public void setConfirm(Command confirm) {
		this.confirm = confirm;
	}

	public Command getCancel() {
		return cancel;
	}

	public void setCancel(Command cancel) {
		this.cancel = cancel;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	/**
	 * @return the innerPage
	 */
	public Page getInnerPage() {
		return innerPage;
	}

	/**
	 * @param innerPage the innerPage to set
	 */
	public void setInnerPage(Page innerPage) {
		this.innerPage = innerPage;
	}
	
}
